package fr.ece.ing4.si.stopwatch;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class StopWatch extends JFrame implements ActionListener {

	private static final long serialVersionUID = -8703843689450789725L;
	private boolean running;
	JButton startStopButton;
	JButton resetButton;
	JLabel timeLabel;
	int count=0;

	@Override
	protected void frameInit() {
		super.frameInit();
		getContentPane().setLayout(new FlowLayout());
		startStopButton = new JButton();
		resetButton = new JButton();
		timeLabel = new JLabel();
		resetButton.setText("Reset");
		timeLabel.setText("0");
		getContentPane().add(startStopButton);
		getContentPane().add(timeLabel);
		getContentPane().add(resetButton);

		startStopButton.addActionListener(this);
		resetButton.addActionListener(this);
		
		Thread t = new Thread(new Counter());
		t.start();
	}

	public void actionPerformed(final ActionEvent event) {
		if(event.getSource().equals(resetButton)){
			resetCounting();
		}
		else{
			if (running)
				stopCounting();
			else
				startCounting();			
		}
	}

	private void startCounting() {
		running = true;
	}

	private void stopCounting() {
		running = false;
	}
	
	private void resetCounting(){
		timeLabel.setText("0");
		count=0;
	}
	
	private class Counter implements Runnable{
		@Override
		public void run() {
			while(true)
			{
				if(running){
					startStopButton.setText("Stop");
					while(running){
						count++;
						timeLabel.setText(String.format("%d", count));
						try {
							Thread.sleep(100);
						} catch (InterruptedException ex) {
							throw new RuntimeException(ex);
						}
					}
				}
				else{
					System.out.println("coucou");
					if(count==0){
						startStopButton.setText("Start");
						}
					else{
						startStopButton.setText("Resume");
					}
				}
			}
			
		}
		
	}

	
}
